package live.jipiao.dao;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import live.api.impl.FlightReqRes;
import live.common.AirParam;
import live.common.Format;

public class WebServicesSub {

	static WebServicesSub instance = null;

	public synchronized static WebServicesSub getInstance() {
		if (instance == null) {
			instance = new WebServicesSub();
		}
		return instance;
	}

	/**
	 * 封装传递参数，并返回接口处理结果
	 * 
	 * @param parameters
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
	public String returnResult(Map<String, String> parameters) {
		String postData = "";
		if (parameters != null && parameters.size() > 0) {
			List keys = new ArrayList(parameters.keySet());
			Collections.sort(keys);
			for (int i = 0; i < keys.size(); i++) {
				String key = (String) keys.get(i);
				Object value = parameters.get(key);
				if (i == keys.size() - 1) {
					postData += key + "=" + value;
				} else {
					postData += key + "=" + value + "&";
				}
			}
		}
		return returnResult(postData, parameters);
	}

	/**
	 * 提交信息到接口
	 * 
	 * @param strData
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 *             MalformedURLException,IOException,UnsupportedEncodingException
	 */
	@SuppressWarnings("unchecked")
	private String returnResult(String strData, Map map) {
		// 提交地址
		HttpURLConnection httpURLConnection;
		StringBuilder sb = null;
		String nodeValue=null;
		try {
			String encodeing = "GB2312";
			map.put("service_id", map.get("service"));
			map.put("requestData", strData);
			String spec = AirParam.POST_URL;
			URL url;
			url = new URL(spec);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setDoOutput(true);// 打开写入属性
			httpURLConnection.setDoInput(true);// 打开读取属性
			httpURLConnection.setRequestMethod("POST");// 设置提交方法
			httpURLConnection.addRequestProperty("ContentType",
					"application/x-www-form-urlencoded");
			httpURLConnection.setConnectTimeout(1000 * 60 * 5);// 连接超时时间
			httpURLConnection.setReadTimeout(1000 * 60 * 5);
			httpURLConnection.connect();
			BufferedWriter out;
			out = new BufferedWriter(new OutputStreamWriter(httpURLConnection
					.getOutputStream(), encodeing));
			out.write(strData);
			out.flush();
			out.close();
			// 要post的数据，多个以&符号分割
			BufferedReader in = new BufferedReader(
					new InputStreamReader((InputStream) httpURLConnection
							.getInputStream(), encodeing));
			String line = null;
			sb = new StringBuilder();
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			nodeValue = returnNodeValue(sb.toString(), "is_success");
			if (Format.getInstance().isNotNullOrEmpty(map.get("service"))) {
				if (nodeValue.trim().equals("F")) {
					map.put("resData", returnNodeValue(sb.toString(), "error"));
				}
			}
			in.close();
			httpURLConnection.disconnect();// 断开连接
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
//			map.put("remark", e.getLocalizedMessage());
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
//			map.put("remark", e.getLocalizedMessage());
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
//			map.put("remark", e.getLocalizedMessage());
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			map.put("remark", e.getLocalizedMessage());
			e.printStackTrace();
		} catch (Exception e) {
			// TODO: handle exception
//			map.put("remark", e.getLocalizedMessage());
			e.printStackTrace();
		} finally {
			if(!map.get("service").equals("GetFlight")){
				FlightReqRes.insertSendRequest(map);
			}else{
				if (nodeValue.trim().equals("F")) {
					FlightReqRes.insertSendRequest(map);
				}
			}
			return sb.toString();
		}
	}

	@SuppressWarnings("finally")
	private String returnNodeValue(String xml, String qname) {
		String nodeValue = null;

		try {
			Document doc = DocumentHelper.parseText(xml);

			Element element = doc.getRootElement();

			nodeValue = element.elementText(qname);

		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} finally {
			return nodeValue;
		}

	}
}
